package com.hy.service.impl;

import com.hy.appbase.dozer.DozerBase;
import com.hy.appbase.exception.BusinessException;
import com.hy.bo.result.InternalGazetteerTreeRetBo;
import com.hy.mapper.InternalGazetteerMapper_My;
import com.hy.model.InternalGazetteerNode;
import com.hy.service.IInternalGazetteerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class InternalGazetteerServiceImpl extends DozerBase implements IInternalGazetteerService {

    @Autowired
    private InternalGazetteerMapper_My internalGazetteerMapper_my;

    @Override
    public List<InternalGazetteerTreeRetBo> findAllNode() {
        List<InternalGazetteerNode> internalGazetteerNodes = internalGazetteerMapper_my.getNodeTree();
        if(internalGazetteerNodes.isEmpty()){
            throw new BusinessException("没有数据");
        }
        List<InternalGazetteerTreeRetBo> internalGazetteerTreeRetBoList = new ArrayList<InternalGazetteerTreeRetBo>();
        formaterToTreeGird(internalGazetteerNodes,internalGazetteerTreeRetBoList,1,"");
        return internalGazetteerTreeRetBoList;
    }

    private void formaterToTreeGird(List<InternalGazetteerNode> internalGazetteerNodes,List<InternalGazetteerTreeRetBo> internalGazetteerTreeRetBoList,int level, String clazz){
        for(InternalGazetteerNode internalGazetteerNode:internalGazetteerNodes) {
            InternalGazetteerTreeRetBo internalGazetteerTreeRetBo = getDozerMapper().map(internalGazetteerNode,InternalGazetteerTreeRetBo.class);
            internalGazetteerTreeRetBo.setLevel(level);
            if(level==1) {
                internalGazetteerTreeRetBo.setClazz("");
            } else {
                internalGazetteerTreeRetBo.setClazz(clazz);
            }
            internalGazetteerTreeRetBoList.add(internalGazetteerTreeRetBo);


            if(internalGazetteerNode.getNext().size()>0) {
                if(StringUtils.isNotBlank(internalGazetteerTreeRetBo.getClazz())){
                    clazz = internalGazetteerTreeRetBo.getClazz()+" "+internalGazetteerTreeRetBo.getId();
                } else {
                    clazz = internalGazetteerTreeRetBo.getId();
                }
                internalGazetteerTreeRetBo.setHasChild(true);
                int nextLevel = level + 1;
                formaterToTreeGird(internalGazetteerNode.getNext(),internalGazetteerTreeRetBoList,nextLevel,clazz);
            }else {
                internalGazetteerTreeRetBo.setHasChild(false);
            }
        }
    }
}
